package com.changan.service.impl;

import com.alibaba.fastjson.JSON;
import com.changan.entity.Menu;
import com.changan.mapper.MenuMapper;
import com.changan.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changan.utils.JsonUtils;
import com.changan.utils.MenuTreeBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author NieChangan
 * @since 2022-12-13
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public List<Menu> findMenuTree() {
        String key = "menuList";
        List<Menu> menuList = new ArrayList<>();
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        if(!redisTemplate.hasKey(key)){
            //说明redis中是不存在菜单栏的
            //从数据库中获取
            List<Menu> rootMenu = this.baseMapper.selectList(null);
            menuList = MenuTreeBuilder.build(rootMenu);
            String s = JsonUtils.objectToJson(menuList);
            //并且需要将menuList存入到redis中
            //根据redis得这个一个倒计时得功能可以用来存放验证码  60s
            operations.set(key,s,10, TimeUnit.SECONDS);
        }else{
            //表示redis中包含menuList
            Object o = operations.get(key);
            //需要将Object的对象转换成List<Menu>的对象
            menuList = JSON.parseObject(operations.get(key).toString(),ArrayList.class);
            //menuList = JsonUtils.jsonToList(o.toString(), Menu.class);
        }
        return menuList;
    }



    @Override
    public List<Long> findOpenIds() {
        return null;
    }
}
